using Items;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ContainerUI_Panel : ContainerUI
{
    public Sprite frameOfItem;
    [SerializeField]
    private Transform transform_content;
    private Scrollbar bar;
    public EItem screenCondition;

    private MyCanvasGrounp myCanvasGrounp;

    [HideInInspector]
    public float offset;

    private const int NUM_ITEM = 50;
    private readonly List<GameObject> items = new List<GameObject>();
    private int curNum;

    protected override void Awake()
    {
        base.Awake();
        bar = GetComponentInChildren<Scrollbar>();
        RectTransform rectTransform = GetComponent<RectTransform>();
        offset = rectTransform.rect.width / 1600 * Screen.width;
        myCanvasGrounp = GetComponent<MyCanvasGrounp>();
        manager = GetComponent<ContainerUI_Manager>();
    }

    protected override void Start()
    {
        base.Start();
        GenerateItem();
    }

    private void GenerateItem()
    {
        GameObject prototype = GetComponentInChildren<ItemUI>().gameObject;
        prototype.SetActive(false);
        for (int i = 0; i < NUM_ITEM; i++)
        {
            items.Add(Instantiate(prototype, transform_content.transform));
        }
        Destroy(prototype);
        curNum = 0;
    }

    public void Refresh()
    {
        if (container == null)
            return;
        InstallItem();
        bar.value = 1;
    }

    private void InstallItem()
    {
        List<ItemStack> _items = container.GetAllItem(screenCondition);
        GameObject obj;
        int i = 0;
        for (; i < _items.Count; ++i)
        {
            obj = items[i];
            if (i >= curNum)
                obj.SetActive(true);
            obj.GetComponent<ItemUI>().Initialize(_items[i], frameOfItem);
        }
        for (; i < curNum; ++i)
        {
            items[i].SetActive(false);
        }
        curNum = _items.Count;
    }

    protected override void OnVisibleChange(bool visible)
    {
        base.OnVisibleChange(visible);
        if (visible)
        {
            myCanvasGrounp.Visible = true;
            Refresh();
            container.ContentChange += Refresh;
        }
        else
        {
            myCanvasGrounp.Visible = false;
            if (container != null)
                container.ContentChange -= Refresh;
        }
    }
}
